package main

import "log"

/* 访问请求的流控制 Token */

type ConnLimiter struct {
	concurrentConn int
	bucket         chan int
}

// NewConnLimiter 工厂函数
func NewConnLimiter(cc int) *ConnLimiter {
	return &ConnLimiter{
		concurrentConn: cc,
		bucket:         make(chan int, cc),
	}
}

// GetConn 获取连接 即Token
func (cl *ConnLimiter) GetConn() bool {
	if len(cl.bucket) >= cl.concurrentConn {
		log.Printf("Reached the rate limitation.")
		return false
	}
	// 如果token没有满可以继续加入
	cl.bucket <- 1
	return true
}

// ReleaseConn 释放token
func (cl *ConnLimiter) ReleaseConn() {
	c := <-cl.bucket
	log.Printf("New connction coming:%d", c)
}
